package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.MD5Utils;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void delete(Long id) {
        employeeMapper.deleteRelation(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Employee employee, Long[] ids) {
        // 保存之后就有id了
        employee.setPassword(MD5Utils.getCipher(employee.getPassword()));
        employeeMapper.insert(employee);
        //System.out.println(employee.getId());
        // 关联关系
        if (ids != null && ids.length > 0) {
            for (Long roleId : ids) {
                System.out.println(roleId);
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.deleteRelation(employee.getId());
        employeeMapper.updateByPrimaryKey(employee);
        if (ids != null && ids.length > 0) {
            for (Long roleId : ids) {
                System.out.println(roleId);
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        //int count = employeeMapper.selectForCount(qo);
        //if(count == 0) {
        //    PageResult<Employee> pageResult = new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), Collections.emptyList(), count);
        //    return pageResult;
        //}
        //// 获取总页数
        //int totalPage =  count % qo.getPageSize() == 0?
        //        count / qo.getPageSize() : count / qo.getPageSize() + 1;
        //// 判断当前页是否大于总页数, 如果是, 把总页数作为当前页来查询
        //qo.setCurrentPage(totalPage <= qo.getCurrentPage() ? totalPage : qo.getCurrentPage());

        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<>(employees);
    }

    @Override
    public Employee login(String username, String password) {
        if (!StringUtils.hasText(username)) {
            throw new LogicException("用户名不能为空");
        }
        if (!StringUtils.hasText(password)) {
            throw new LogicException("密码不能为空");
        }
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null) {
            throw new LogicException("用户名或密码错误");
        }
        if (!employee.isStatus()) {
            throw new LogicException("用户已被禁用, 请联系管理员");
        }
        return employee;
    }

    @Override
    public void updatePassword(String oldPassword, String newPassword) {
        if (!StringUtils.hasText(newPassword) || newPassword.indexOf(" ") != -1) {
            throw new RuntimeException("密码不能为空,不能包含空格");
        }
        Employee employee = UserContext.getCurrentUser();

        if (!employee.getPassword().equals(MD5Utils.getCipher(oldPassword.trim()))) {

            throw new RuntimeException("原密码输入有误");
        }
        employee.setPassword(MD5Utils.getCipher(newPassword));
        employeeMapper.updatePassword(employee);
    }

    @Override
    public void resetPassword(Long id, String newPassword) {
        Employee employee = new Employee();
        employee.setId(id);
        employee.setPassword(MD5Utils.getCipher(newPassword));
        if (!StringUtils.hasText(newPassword) || newPassword.indexOf(" ") != -1) {
            throw new RuntimeException("密码不能为空,不能包含空格");
        }
        if (employeeMapper.updatePassword(employee) < 1) {
            throw new RuntimeException("服务器异常");
        }
    }

    @Override
    public void updateStatus(Long id) {
        employeeMapper.updateStatus(id);
    }

    @Override
    public void batchDelete(Long[] ids) {
        for (Long id : ids) {
            employeeMapper.deleteRelation(id);
        }
        employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee selectByName(String name) {
        return employeeMapper.selectByName(name);
    }

    @Override
    public Workbook exportXls() {
        // 查询所有员工
        List<Employee> employees = employeeMapper.selectAll();
        // 创建一个excel
        Workbook wb = new HSSFWorkbook();
        // 创建excel中的表
        Sheet sheet = wb.createSheet("员工通讯录");
        // 创建一行数据, 从0开始
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        row.createCell(3).setCellValue("状态");
        row.createCell(4).setCellValue("部门");
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            // 创建一行数据, 从0开始
            row = sheet.createRow(i + 1);
            // 创建单元格, 写入内容到单元格
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
            System.out.println(employee.isStatus());
            row.createCell(3).setCellValue(employee.isStatus() ? "正常" : "禁用");
            row.createCell(4).setCellValue(employee.getDept().getName());
        }
        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        // 读取第0张sheet表
        Sheet sheet = wb.getSheetAt(0);
        // 获取最后一行的索引, 判断有多少行数据 用于遍历读取
        int lastRowNum = sheet.getLastRowNum();
        // 获取列数
        System.out.println("ColumnNum: " + sheet.getRow(0).getPhysicalNumberOfCells());
        // 获取行数
        System.out.println("RowNum: " + sheet.getPhysicalNumberOfRows());
        // 获取最后一行的下标
        System.out.println("lastRowNum: " + lastRowNum);

        // 标题行不用读取
        for (int i = 0; i < lastRowNum; i++) {
            // 读取每一行数据
            Row row = sheet.getRow(i + 1);
            Employee employee = new Employee();
            // 如果第一个和第二个单格为空, 不继续往下查询
            if (row.getCell(0) == null || row.getCell(1) == null) {
                return;
            }
            try {
                employee.setName(row.getCell(0).getStringCellValue());
            } catch (Exception e) {
                e.printStackTrace();
                throw new LogicException("第" + (row.getRowNum() + 1) + "行,第" + (row.getCell(0).getColumnIndex() + 1) + "名字输入格式有误");
            }
            employee.setEmail(row.getCell(1).getStringCellValue());
            if (row.getCell(2).getCellType() == CellType.NUMERIC) {
                employee.setAge((int) row.getCell(2).getNumericCellValue());
            } else {
                employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            }
            employeeMapper.insert(employee);
        }
    }

    @Override
    public Long getCurrentDept() {
        return UserContext.getCurrentUser().getDept().getId();
    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        return employeeMapper.selectByRoleSn(sns);
    }


}
